1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.base;
18  
19  import static com.google.common.base.Preconditions.checkNotNull;
20  
21  import java.util.Collections;
22  import java.util.HashMap;
23  import java.util.Map;
24  
25  import javax.annotation.Nullable;
26  
27  /**
28   * This class provides default values for all Java types, as defined by the JLS.
29   *
30   * @author Ben Yu
31   * @since 1.0
32   */
33  public final class Defaults {
34    private Defaults() {}
35  
36    private static final Map<Class<?>, Object> DEFAULTS;
37  
38    static {
39      // Only add to this map via put(Map, Class<T>, T)
40      Map<Class<?>, Object> map = new HashMap<Class<?>, Object>();
41      put(map, boolean.class, false);
42      put(map, char.class, '\0');
43      put(map, byte.class, (byte) 0);
44      put(map, short.class, (short) 0);
45      put(map, int.class, 0);
46      put(map, long.class, 0L);
47      put(map, float.class, 0f);
48      put(map, double.class, 0d);
49      DEFAULTS = Collections.unmodifiableMap(map);
50    }
51  
52    private static <T> void put(Map<Class<?>, Object> map, Class<T> type, T value) {
53      map.put(type, value);
54    }
55  
56    /**
57     * Returns the default value of {@code type} as defined by JLS --- {@code 0} for numbers, {@code
58     * false} for {@code boolean} and {@code '\0'} for {@code char}. For non-primitive types and
59     * {@code void}, null is returned.
60     */
61    @Nullable
62    public static <T> T defaultValue(Class<T> type) {
63      // Primitives.wrap(type).cast(...) would avoid the warning, but we can't use that from here
64      @SuppressWarnings("unchecked") // the put method enforces this key-value relationship
65      T t = (T) DEFAULTS.get(checkNotNull(type));
66      return t;
67    }
68  }